package main

import (
	"cart_srv/cart"
	"cart_srv/global"
	"cart_srv/hanlder"
	_ "cart_srv/initialize"
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	g := grpc.NewServer()
	s := hanlder.CartService{}

	cart.RegisterCartServer(g, &s)

	grpc_health_v1.RegisterHealthServer(g, health.NewServer())
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.AppConf.Ip, global.AppConf.Port))
	if err != nil {
		zap.S().Error(err)
		return
	}

	go func() {
		err = g.Serve(listen)
		if err != nil {
			zap.S().Error(err)
			return
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.AppConf.ConsulConfig.Host, global.AppConf.ConsulConfig.Port)
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Error(err)
		return
	}
	err = client.Agent().ServiceDeregister(global.ServiceId)
	if err != nil {
		zap.S().Error("注销服务失败")
		return
	}
	zap.S().Info("注销服务成功")
}
